﻿using System;
using System.Net;
using System.Net.Mail;
using Monkey.Framework.Configuration;

namespace Monkey.Framework.Email
{
    public class SmtpService : IEmailService
    {
        private readonly SmtpClient _clientMail;

        /// <summary>
        /// Initializes a new instance of the <see cref="SmtpService"/> class.
        /// </summary>
        public SmtpService()
        {
            var host = EmailSettings.Host;
            var sPort = EmailSettings.Port;
            var mailUser = EmailSettings.EmailFrom;
            var mailPass = EmailSettings.EmailPass;
            var ssl = EmailSettings.Ssl;
            var isSsl = (ssl == "true");
            int port;
            int.TryParse(sPort, out port);

            _clientMail = new SmtpClient
                              {
                                  Host = host,
                                  Port = port,
                                  Credentials = new NetworkCredential(mailUser, mailPass),
                                  EnableSsl = isSsl
                              };
        }

        /// <summary>
        /// Sends the mail.
        /// </summary>
        /// <param name="from">From.</param>
        /// <param name="to">To.</param>
        /// <param name="cc">The cc.</param>
        /// <param name="bcc">The BCC.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="body">The body.</param>
        public void SendMail(string from, string to, string cc, string bcc, string subject, string body)
        {
            var mM = new MailMessage {From = new MailAddress(@from, EmailSettings.EmailDisplayName)};

            mM.To.Add(to);
            if (!string.IsNullOrEmpty(bcc)) mM.Bcc.Add(bcc);
            if (!string.IsNullOrEmpty(cc)) mM.CC.Add(cc);
            mM.Subject = subject;
            mM.Body = body;
            mM.IsBodyHtml = true;

            switch (EmailSettings.EmailPriority)
            {
                case "High":
                    mM.Priority = MailPriority.High;
                    break;
                case "Low":
                    mM.Priority = MailPriority.Low;
                    break;
                default:
                    mM.Priority = MailPriority.Normal;
                    break;
            }
            

            _clientMail.Send(mM);
        }
    }

}
